<script src="/vender/jstree/jstree.min.js"></script>
<link rel="stylesheet" href="/vender/jstree/jstree.css" media="all">

<div class="layui-form" lay-filter="form-list" id="form-list" style="padding: 20px 30px 0 0;">
    <div class="layui-form-item">
        <label class="layui-form-label"><span class="required">*</span>角色名称</label>
        <div class="layui-input-block">
            <input type="text" name="role_name" lay-verify="required" placeholder="请输入角色名称" autocomplete="off" class="layui-input" value="{$role['role_name']|default=''}">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"><span class="required">*</span>权限</label>
        <div class="layui-input-block">

            <div class="treeview-tools clearfix">
                <div class="btn-group btn-group-sm pull-right" role="group">
                    <button class="layui-btn layui-btn-primary layui-btn-sm btn-unfold">展开</button>
                    <button class="layui-btn layui-btn-primary layui-btn-sm btn-fold">折叠</button>
                </div>
            </div>
            <div class="pagetree margin-top-10">
                <div data-plugin="slimScroll" data-user="240px">
                    <div data-plugin="treeview"></div>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">角色描述</label>
        <div class="layui-input-block">
            <textarea name="description" placeholder="请输入角色描述" class="layui-textarea">{$role['description']|default=''}</textarea>
        </div>
    </div>
    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="form-submit" id="form-submit" value="确认添加" class="btn-treeview">
        <input type="hidden" name="id" value="{$role['id']|default=''}">
    </div>
</div>
<script>
    //Demo
    layui.use('form', function(){
        var form = layui.form;

        //监听提交
        form.on('submit(form-submit)', function(data){
            getMenuIds();
            var field = data.field; //获取提交的字段
            field.menu_ids =  getMenuIds();
            console.log(field);
            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            //提交 Ajax 成功后，关闭当前弹层并重载表格
            $.post("{:url('admin/user_role/save')}",field,function (ret) {
                if (ret.code == 0){
                    layer.msg(ret.msg,{icon:6,time:1000},function () {
                        parent.layui.table.reload('demo'); //重载表格
                        parent.layer.close(index); //再执行关闭
                    })
                }else{
                    layer.msg(ret.msg,{icon:5,time:1000})
                }
            });

            return false;
        });
    });

    var id = $('input[name="id"]').val();
    //树节点
    $('[data-plugin="treeview"]').data('jstree', false).empty().jstree({
        "checkbox": {
            "keep_selected_style": false
        },
        "plugins": ["checkbox", "search"],
        "core": {
            'data': {
                "url": "/admin/user_role/menuList?roleId="+id,
                "dataType": "JSON"
            }
        }
    });

    $(document).on('click', '.btn-unfold', function () { // 展开所有树节点
        $('[data-plugin="treeview"]').jstree().open_all();
    });

    $(document).on('click', '.btn-fold', function () { // 折叠所有树节点
        $('[data-plugin="treeview"]').jstree().close_all();
    });

    function getMenuIds() { // 保存菜单树ID
     var $treeview = $('[data-plugin="treeview"]'),
         data = [],
         checkedData = $treeview.jstree("get_checked");

     var treeData = function ($el) {
         var $items = $el.children('ul').children('li'), i = 0;

         for (; i < $items.length; i++) {
             if ($items.eq(i).attr("aria-selected") === "true" || $items.eq(i).children('a').find('i.jstree-undetermined').size() > 0) {
                 data.push($items.eq(i).prop('id'));
             }
             if ($items.eq(i).children("ul").size() > 0) {
                 treeData($items.eq(i));
             }
         }
     };

     var treeArry = function (checkedData) {
         var item = checkedData.shift(),
             temp = [];

         for (var n in data) {
             if (item !== data[n]) {
                 temp.push(item);
             }
         }
         if (temp.length === data.length) {
             data.push(item);
         }
         if (checkedData.length > 0) {
             treeArry(checkedData);
         }
     };

     treeData($treeview);
     treeArry(checkedData);
     return data;
    };
</script>